﻿using System;
using System.Xml.Serialization;
using Framework;
using Koala.Framework.FileSystems.App_Data;

namespace Koala.JiraTool.Core
{
    internal class DataPersistence : IDataPersistence
    {
        private readonly IAppDataFolder _appDataFolder;

        public DataPersistence(IAppDataFolder appDataFolder)
        {
            _appDataFolder = appDataFolder;
        }

        #region Implementation of IDataPersistence

        public void Save(string key, object data)
        {
            var serializer = new XmlSerializer(data.GetType());
            if (_appDataFolder.FileExists(key))
            {
                _appDataFolder.DeleteFile(key);
            }
            var storageFile = _appDataFolder.CreateFile(key);
            using (var stream = storageFile.OpenWrite())
            {
                serializer.Serialize(stream, data);
            }
        }

        public void Save(object data)
        {
            Save(data.GetType().Name, data);
        }

        public object Get(string key, Type type)
        {
            if (!_appDataFolder.FileExists(key))
                return null;
            var serializer = new XmlSerializer(type);
            using (var stream = _appDataFolder.GetFile(key).OpenRead())
            {
                return serializer.Deserialize(stream);
            }
        }

        public T Get<T>(string key) where T : class ,new()
        {
            return (T)Get(key, typeof(T));
        }

        public object Get(Type type)
        {
            return Get(type.Name, type);
        }

        public T Get<T>() where T : class, new()
        {
            return (T)Get(typeof(T));
        }

        #endregion Implementation of IDataPersistence
    }
}